﻿using Jst.Application.Contracts.Services;
using Microsoft.Extensions.Caching.Memory;

namespace Jst.Infrastructure.Caching
{
    /// <summary>
    /// 实例化缓存接口ICaching
    /// </summary>
    public class MemoryCachingProvider : ICachingProvider
    {
        private readonly IMemoryCache _cache;
        private readonly MemoryCacheEntryOptions _defaultOptions;

        public MemoryCachingProvider(IMemoryCache cache)
        {
            _cache = cache;
            _defaultOptions = new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromMinutes(30));
        }

        public Task<string?> GetAsync(string key)
        {
            return Task.FromResult(_cache.Get<string>(key));
        }

        public Task SetAsync(string key, string value, TimeSpan ttl)
        {
            var options = new MemoryCacheEntryOptions()
                .SetAbsoluteExpiration(ttl);
            _cache.Set(key, value, options);
            return Task.CompletedTask;
        }

        public Task DelAsync(string key)
        {
            _cache.Remove(key);
            return Task.CompletedTask;
        }
    }
}
